package com.learn.demo.nio;

import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.util.Iterator;
import java.util.Set;

public class NIODemoServer {
    public static void main(String[] args) throws Exception {
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        serverSocketChannel.configureBlocking(false);
        ServerSocket serverSocket = serverSocketChannel.socket();
        serverSocket.bind(new InetSocketAddress(7777));
        System.out.println("服务器启动，监听7777端口");
        Selector selector = Selector.open();
        //注册监听selector OP_ACCEPT事件
        serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
        while (true) {
            if (selector.select(1000) == 0) {
                //等待客户端连接
            }
            Set<SelectionKey> selectionKeys = selector.selectedKeys();
            Iterator<SelectionKey> selectionKeyIterator = selectionKeys.iterator();
            while (selectionKeyIterator.hasNext()) {
                SelectionKey selectionKey = selectionKeyIterator.next();
                if (selectionKey.isAcceptable()) {
                    ServerSocketChannel server = (ServerSocketChannel) selectionKey.channel();
                    System.out.println("客户端连接,OP_ACCEPT事件，selectionKey.hashCode()：" + selectionKey.hashCode());
                    SocketChannel client = server.accept();
                    client.configureBlocking(false);
                    //注册监听selector OP_READ事件
                    client.register(selector, SelectionKey.OP_READ);
                }
                if (selectionKey.isReadable()) {
                    SocketChannel client = (SocketChannel) selectionKey.channel();
                    ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
                    client.read(byteBuffer);
                    byteBuffer.flip();
                    System.out.println("客户端连接,OP_READ事件,selectionKey.hashCode()：" + selectionKey.hashCode());
                    System.out.println("收到客户端消息：" + new String(byteBuffer.array(), 0, byteBuffer.capacity()));
                }
                selectionKeyIterator.remove();
            }
        }
    }
}
